/**
 * 
 */
package com.kelaite.procurement.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.kelaite.procurement.constants.Constants;
import com.kelaite.procurement.constants.UserTypeEnum;
import com.kelaite.procurement.constants.VendorStatusEnum;
import com.kelaite.procurement.dto.UserDTO;
import com.kelaite.procurement.entity.TBank;
import com.kelaite.procurement.entity.TCompany;
import com.kelaite.procurement.entity.TIndustry;
import com.kelaite.procurement.entity.TOrganizationType;
import com.kelaite.procurement.entity.TProvince;
import com.kelaite.procurement.entity.TUser;
import com.kelaite.procurement.entity.TVendor;
import com.kelaite.procurement.entity.TVendorUser;
import com.kelaite.procurement.service.BankService;
import com.kelaite.procurement.service.CityService;
import com.kelaite.procurement.service.CompanyService;
import com.kelaite.procurement.service.IndustryService;
import com.kelaite.procurement.service.OrganizationTypeService;
import com.kelaite.procurement.service.ProvinceService;
import com.kelaite.procurement.service.UserService;
import com.kelaite.procurement.service.VendorService;
import com.kelaite.procurement.service.VendorUserService;
import com.kelaite.procurement.utils.ConvertTime;
import com.kelaite.procurement.utils.ConvertUtil;
import com.kelaite.procurement.utils.CurrentUserUtils;
import com.kelaite.procurement.utils.EncryptUtils;

/**
 * @author yuanchangwei
 *
 */
@Controller
@RequestMapping("/register")
public class RegisterController {

	
	@Autowired
	private ProvinceService provinceService;
	
	@Autowired
	private CompanyService companyService;
	
	@Autowired
	private OrganizationTypeService organizationTypeService;
	@Autowired
	private BankService bankService;
	
	@Autowired
	private CityService cityService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private VendorService vendorService;
	
	@Autowired
	private IndustryService industryService;
	
	@Autowired
	private VendorUserService vendorUserService;
	
	
	@RequestMapping(value = "/create", method = {RequestMethod.GET, RequestMethod.POST})
	public String init(Model model) {
		this.initDate(model);
		return "register";
	}
	
	@RequestMapping(value = "/createCompany", method = {RequestMethod.GET, RequestMethod.POST})
	public String createCompany(@ModelAttribute TCompany company,HttpServletRequest request, Model model){
		company.setBusinessType((short)2);
		String orgType = request.getParameter("orgType");
		TOrganizationType tOrganizationType = organizationTypeService.getObject(Long.parseLong(orgType));
		company.settOrganizationType(tOrganizationType);
		if(companyService.findByCompanyName(company.getCompanyName().trim()) == null){
			companyService.save(company);
		}else{
			// 用户已经存在
			request.setAttribute("errorMsg", "公司已经存在!");
			model.addAttribute("company", company);
		}
		this.initDate(model);
		return "register";
	}
	
	@RequestMapping(value = "/createUser", method = {RequestMethod.GET, RequestMethod.POST})	
	public String createUser(@ModelAttribute("user") TUser user, BindingResult result, HttpServletRequest request, Model model){
		String companyId = request.getParameter("companyId");
		TCompany company = companyService.getObject(Long.parseLong(companyId));
		String clientId = request.getParameter("clientId");
		TCompany client = companyService.getObject(Long.parseLong(clientId));
		if (userService.countByTCompany(company) > 0){
			user.setIsCompanyAdmin(0);
					
		} else {
			user.setIsCompanyAdmin(1);
		}
		user.setPassword(EncryptUtils.encryptSalt(user.getPassword()));
		TUser qUser = userService.findByUsername(user.getUsername().trim());
		TUser savedUser = null;
		if (qUser == null){
			user.setEmail(user.getMobilePhone());
			user.setRealName(user.getUsername().trim());
			user.setType(Short.parseShort(String.valueOf(UserTypeEnum.SUPPLIER.getVal())));
			user.settCompany(company);
			savedUser = userService.save(user);	
			
			Date currentDate = new Date();
			TVendor vendor = new TVendor();
			vendor.setCreatedBy(savedUser.getUsername());
			vendor.setDelete(false);
			vendor.setGmtCreateTime(currentDate);
			vendor.setGmtUpdateTime(currentDate);
			vendor.setGrade("B");
			vendor.setGradeToDate(currentDate);
			Date oneYearDate = ConvertTime.plusDaysDate(currentDate, Constants.ONE_YEAR);
			vendor.setGradeToDate(oneYearDate);
			vendor.setStatus(Short.parseShort(String.valueOf(VendorStatusEnum.EFFECTIVE_SUPPLIER.getVal())));
			vendor.setStatusFromDate(currentDate);
			vendor.setStatusToDate(oneYearDate);
			vendor.settClient(client);
			vendor.settSupplier(company);
			vendor.setUpdatedBy(savedUser.getUsername());
			vendor.setUsersLimitNum(5);
			vendor.setUsersLimitNum(Constants.DEFAULT_USER_LIMIT_NUM);
			vendor.setVendorName(company.getCompanyName());
			vendor.setVendorNo("");
			TVendor savedVendor = this.vendorService.save(vendor);
			
			TVendorUser vendorUser = new TVendorUser();
			vendorUser.setBusinessType(Constants.COMPANY_BUSINESS_TYPE_PARTY_SECOND);
			vendorUser.setStatus(Constants.VENDOR_USER_STATUS_ACTIVE);
			vendorUser.settVendor(savedVendor);
			vendorUser.settUser(savedUser);
			this.vendorUserService.save(vendorUser);
			
			// request.setAttribute("errorMsg", "用户注册成功!");
			//  自动登录
			UserDTO dto = ConvertUtil.convertObj(savedUser, UserDTO.class);
			CurrentUserUtils.getInstance().setUser(dto);
			return "redirect:/supplier/index.htm";
		} else {
			// 用户已经存在
			request.setAttribute("errorMsg", "该用户已经存在！");
			model.addAttribute("user", user);
			this.init(model);			
			return "register";
		}
	}
	
	private void initDate(Model model){
		// province
		List<TProvince> pList = provinceService.getAll();
		model.addAttribute("pList", pList);
		// 乙方公司
		List<TCompany> companyList = companyService.findByBusinessType((short)2);
		model.addAttribute("companyList", companyList);
		//甲方公司
		List<TCompany> clientList = companyService.findByBusinessType((short)1);
		model.addAttribute("clientList", clientList);
		// company
		TCompany company = new TCompany();
		model.addAttribute("company", company);
		// organization Type
		List<TOrganizationType> orgList = organizationTypeService.getAll();
		model.addAttribute("orgList", orgList);
		// TUser
		TUser user = new TUser();
		model.addAttribute("user", user);
		// Bank
		List<TBank> bankList = bankService.getAll();
		model.addAttribute("bankList", bankList);
		// 行业
		List<TIndustry> industryList = industryService.getAll();
		model.addAttribute("industryList", industryList);
	}
}
